import React, {	Component} from 'react';
import { connect } from 'dva'; //调取接口用
import moment from 'moment';
import { Table, Button, Card, Modal, Form, Icon, Input, Menu, Dropdown, message, TreeSelect, Select, Switch, Row, Col,DatePicker } from 'antd';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import styles from '../Mana/Role.less';
//考勤记录
//select
const Option = Select.Option;
const Search = Input.Search;
//时间戳 转化为时间格式
var Y,M,D,h,m,s="";
function timestampToTime(timestamp){
    var date = new Date(timestamp);//时间戳为10位需*1000，时间戳为13位的话不需乘1000   //* 1000
    Y = date.getFullYear() + '/';
    M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '/';
    D = date.getDate() + ' ';
    h = date.getHours() + ':';  m = date.getMinutes() + ':';  s = date.getSeconds();
    return Y+M+D+h+m+s;
}
//table 列表

var order;//排序
var rowSelections = "";
//table复选框选中
// rowSelection objects indicates the need for row selection
const rowSelection = {
	onChange: (selectedRowKeys, selectedRows) => {
		console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
	},
	onSelect: (record, selected, selectedRows) => {
		rowSelections = new Object(); //声明对象
		rowSelections.selected = selected;
		rowSelections.selectedRows = selectedRows;
		console.log(record, selected, selectedRows);
	},
	onSelectAll: (selected, selectedRows, changeRows) => {
		rowSelections = new Object(); //声明对象
		rowSelections.selected = selected;
		rowSelections.selectedRows = selectedRows;
		console.log(selected, selectedRows, changeRows);
	},
};



//form 表单
const FormItem = Form.Item;
//表单内容
const CollectionCreateForm = Form.create()(
	(props) => {
		const {	visible,title,onCancel,onCreate,form,showModal,dispatch,objs} = props;
		const {getFieldDecorator} = form;
		if(title=="新增"){
			return(
				<Modal
				maskClosable={false}
				destroyOnClose={true}
		        visible={visible}
		        title={title}
		        okText="确定"
		        onCancel={onCancel}
		        onOk={onCreate}
		      > 
		      <Form layout="horizontal">
	          	<FormItem   wrapperCol={{span: 22}}>
		            {getFieldDecorator('childrenId', {
		            	initialValue:objs.childrenId,
		            	rules: [{ required: true, message: '孩子Id不能为空!' }],
		            })(
		               <Input />
		            )}
	          	</FormItem>
	          	<FormItem label="具体原因" labelCol={{span: 4}}  wrapperCol={{span: 18}}>
		            {getFieldDecorator('reason', {
		            	initialValue:objs.reason,
		            	rules: [{ required: true, message: '具体原因不能为空!' }],
		            })(
		               <Input />
		            )}
	          	</FormItem>
	        </Form>
	      </Modal>
		);
		}else if(title=="查看"){
			return(
				<Modal
				maskClosable={false}
				destroyOnClose={true}
		        visible={visible}
		        title={title}
		        okText="确定"
		        onCancel={onCancel}
		      > 
		      <Form layout="horizontal">
	          	<FormItem   wrapperCol={{span: 22}}>
		            {getFieldDecorator('childrenId', {
		            	initialValue:objs.childrenId,
		            	rules: [{ required: true, message: '孩子Id不能为空!' }],
		            })(
		               <Input />
		            )}
	          	</FormItem>
	          	<FormItem label="具体原因" labelCol={{span: 4}}  wrapperCol={{span: 18}}>
		            {getFieldDecorator('reason', {
		            	initialValue:objs.reason,
		            	rules: [{ required: true, message: '具体原因不能为空!' }],
		            })(
		               <Input />
		            )}
	          	</FormItem>
	        </Form>
	      </Modal>
		);
		}
		
	}
);

@connect(({ attendance, loading }) => ({
  attendance,
  loading: loading.models.attendance,
}))
@Form.create()
class App extends React.Component {
	state = {
		confirmLoading: false,
		visible: false,
		title: "新增",
		objs: "", //编辑时赋值
	};
	//打开弹窗
	showModal = (falg,record,title) => {
		this.form.resetFields();
		if(title == "新增") {
			this.setState({visible: true,title: title,objs: ""});
		}else{ //查看
			if(!rowSelections || rowSelections.selected == false) {
				message.warning('还未选择数据,无操作');
			}else{
				if(rowSelections.selectedRows.length > 1) {
					message.warning('只能选择一项进行操作');
				}else{
					rowSelections.selectedRows[0].syllabusDateId+=''
					rowSelections.selectedRows[0].dateStatus+=''
					rowSelections.selectedRows[0].isDefault+=''
					this.setState({
						visible: true,
						title: title,
						objs: rowSelections.selectedRows[0],
					});
				}
			}
		}
	}
	//点击取消
	handleCancel = () => {this.setState({visible: false})}
	
	//默认查询数据
	componentDidMount() {
		//默认查询table 数据
		this.props.dispatch({type: 'attendance/fetch_attList'});
	}
	//新增
	handleCreate = (title) => {
		const form = this.form;
		form.validateFields((err, values) => {
			if(err) {	return;}
			console.log('Received values of form: ', values);
			values.startDate=timestampToTime(values.startDate);//开始时间
			values.endDate=timestampToTime(values.endDate);//结束时间
			if(values.dateStatus==undefined)	values.dateStatus=1
			if(values.isDefault==undefined)	values.isDefault=1
			if(values.remark==undefined)	values.remark=""
			form.resetFields();
			if(title == "新增") { //新增
				this.props.dispatch({
					type: 'attendance/add_course_time',
					payload: {...values},
					callback: (res,resMsg) => {
						if(res == 1) message.success(resMsg);
						else message.error(resMsg);
					},
				});
			}
			this.setState({
				visible: false,
			});
		});
	}
	//重置
	handleFormReset = () => {
		const {	form,	dispatch} = this.props;
		form.resetFields();
		this.setState({	formValues: {},});
		dispatch({type: 'attendance/fetch_attList',});
	}
	//排序
	handleForm=()=>{
		const {	dispatch,form} = this.props;
		form.validateFields((err, fieldsValue) => {
			if(err) return;
			const values = {
				...fieldsValue,
				updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
			};
			this.setState({	formValues: values});
			if(values.type ==undefined){values.type =""}
			if(values.userName==undefined){values.userName=""}
			if(values.name==undefined){values.name=""}
			if(values.startTime ==undefined){values.startTime =""}
			if(values.employTime ==undefined){values.employTime =""}
			if(values.order ==undefined){values.order =1}
			dispatch({
				type: 'attendance/fetch_attList',
				payload:{
					...values,
				}
			});
		});
	  }
	
	//查询
	handleSearch = (e) => {
		e.preventDefault();
		const {	dispatch,form} = this.props;
		form.validateFields((err, fieldsValue) => {
			if(err) return;
			const values = {
				...fieldsValue,
				updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
			};
			this.setState({	formValues: values});
			if(values.type ==undefined){values.type =""}
			if(values.userName==undefined){values.userName=""}
			if(values.name==undefined){values.name=""}
			if(values.names==undefined){values.names=""}
			if(values.order ==undefined){values.order =0}
			if(values.updatedAt ==undefined){values.updatedAt =""}
			if(values.startTime ==undefined){values.startTime=""}else{
				values.startTime=moment(values.startTime).format('YYYY-MM-DD');
			}
			if(values.employTime ==undefined){values.employTime=""}else{
				values.employTime=moment(values.employTime).format('YYYY-MM-DD');
			}
			dispatch({
				type: 'attendance/fetch_attList',
				payload:{
					...values,
				}
			});
		});
	}
	onSearch=(value)=>{
		const {	dispatch,form} = this.props;
		value = value.replace(/\+/g, '$aoxin');
		this.props.dispatch({
	  		type: 'attendance/add_attendance',
	      	payload: {
	      		aseChildrenId:value,
	      	},
	      	callback: (res,resMsg) => {
	      	if(res==1){
	      		message.success("打卡成功");
	      		
	      	}else{
	      		message.error("打卡失败");
	      		
	      	}
	      	form.resetFields();
	      },
	    });
	}


	saveFormRef = (form) => {this.form = form;}
	
	renderAdvanForm() {
	    const {getFieldDecorator} = this.props.form;
		return(
			<Form onSubmit={this.handleSearch} layout="inline">
		        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
		         	<Col md={8} sm={24}>
			            <FormItem label="考勤类型">
			              {getFieldDecorator('type')(
			                <Select showSearch    style={{ width: '100%' }} placeholder="请选择">
							    <Option value="0">正常</Option>
							    <Option value="1">迟到</Option>
							    <Option value="5">缺席</Option>
							</Select>
			              )}
			            </FormItem>
		          	</Col>
		          
		          	<Col md={8} sm={24}>
			            <FormItem label="用户电话">
			              {getFieldDecorator('userName')(
			                <Input placeholder="请输入" />
			              )}
			            </FormItem>
		          	</Col>
		          	<Col md={8} sm={24}>
			            <FormItem label="孩子名称">
			              {getFieldDecorator('name')(
			                <Input placeholder="请输入" />
			              )}
			            </FormItem>
		          	</Col>
		         </Row>
		        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
		        	<Col md={8} sm={24}>
			            <FormItem label="上课时间">
			              {getFieldDecorator('startTime')(
			                <DatePicker format="YYYY-MM-DD" style={{ width: '100%' }}/>
			              )}
			            </FormItem>
		         	</Col>
		         	<Col md={8} sm={24}>
			            <FormItem label="下课时间">
			              {getFieldDecorator('employTime')(
			                <DatePicker format="YYYY-MM-DD" style={{ width: '100%' }}/>
			              )}
			            </FormItem>
		         	</Col>
		         	<Col md={8} sm={24}>
		            <FormItem>
			            <span style={{ float: 'right', marginBottom: 24 }}>
				            <Button type="primary" htmlType="submit">查询</Button>
				            <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>重置</Button>
				            <Button type="primary" style={{ marginLeft: 8 }} onClick={this.handleForm}>倒序</Button>
				        </span>
		            </FormItem>
		          </Col>
		         </Row>
		      
		    </Form>
		);
	}
	
	renderSimpleForm() {
	    const { getFieldDecorator } = this.props.form;
	    return (
	    	<Col md={20} sm={24}>
	      	<Form onSubmit={this.handleSearch} layout="vertical">
	            <FormItem >
	              {getFieldDecorator('names')(
	                <Search placeholder="签到码"  enterButton="打卡" size="large" onSearch={this.onSearch}  style={{width:'100%'}}/>
	              )}
	            </FormItem>
	      </Form>
	    </Col>
	  );
	}
	render() {
		const {	visible,title,confirmLoading} = this.state;
		const { attendance: { data=[] }, loading } = this.props;
		const rowKey = function(data) {return data.attendanceId;/*主键id*/};
		const columns = [
		/*{
			title: '序号',
			dataIndex: 'attendanceId',
			key: 'attendanceId',
			width:'70px',
			render: (text, record, index) => {
			return index + 1
			}
		},*/
		{
			title: '用户电话',
			dataIndex: 'userName',
			width:'150px',
			
		},
		{
			title: '孩子名称',
			dataIndex: 'name',
			width:'150px',
		},
		{
			title: '教室名称',
			dataIndex: 'classroomName',
			width:'150px',
			
		},
		{
			title: '课程名称',
			dataIndex: 'courseName',
			width:'150px',
			
		},
		{
			title: '课程类型',
			dataIndex: 'courseType',
			width:'100px',
			render: (text, record, index) =>{
				if(record.courseType==1){
					return "B类"
				}else if(record.courseType==2){
					return "C类"
				}
			} 
			
		},
		{
			title: '课程开始时间',
			dataIndex: 'startTime',
			width:'160px',
			render: val => <span>{moment(val).format('YYYY-MM-DD HH:mm:ss')}</span>,
			
		},
		{
			title: '课程结束时间',
			dataIndex: 'employTime',
			width:'160px',
			render: val => <span>{moment(val).format('YYYY-MM-DD HH:mm:ss')}</span>,
			
		},
		{
			title: '考勤类型',
			dataIndex: 'type',
			width:'150px',
			render: (text, record, index) =>{
				if(record.type==0){
					return "正常"
				}else if(record.type==1){
					return "迟到"
				}else if(record.type==5){
					return "缺席"
				}else{
					return "未打考勤"
				}
			} 
		},
		{
			title: '打卡时间',
			dataIndex: 'cardDate',
			width:'160px',
			render: val => <span>{moment(val).format('YYYY-MM-DD HH:mm:ss')}</span>,
		},
	];
		return(
			<PageHeaderLayout  title="校区管理/出勤管理/打卡记录" >
        		<Card bordered={false}>
	        		<div className={styles.tableList}>
			            <div className={styles.tableListForm}>
			              	{this.renderAdvanForm()}
			               <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
		           			<Col md={2} sm={24}></Col>
			              	{this.renderSimpleForm()}
			               	<Col md={2} sm={24}></Col>
			               	</Row>
			            </div>
						{/*<div className={styles.table_operations} >
					      	<Button  type="primary"  onClick={() => this.showModal('新增')}>新增</Button>
					      	<Button  type="primary" style={{marginLeft:'10px'}}  onClick={() => this.showModal(true,'','查看')}>查看</Button>
					    </div>*/}
					    <CollectionCreateForm
				          	ref={this.saveFormRef}
				         	title={this.state.title}
				          	objs={this.state.objs}
				          	confirmLoading={confirmLoading}
				          	visible={this.state.visible}
				          	onCancel={this.handleCancel} 
				          	onCreate={() => this.handleCreate(this.state.title)}
					    />
					    <Table rowKey={rowKey} columns={columns}  loading={loading}  dataSource={data}  pagination={{ pageSize: 10 }} scroll={{ x: true}}/>
					</div>
	      		</Card>
	   		</PageHeaderLayout>
		)
	}
}
export default() => (<App />)